%%%-------------------------------------------------------------------
%%% File    : p9.erl
%%% Author  : Plamen Dragozov <plamen at dragozov.com>
%%% Description : 
%%% A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
%%% a^(2) + b^(2) = c^(2)
%%% For example, 3^(2) + 4^(2) = 9 + 16 = 25 = 5^(2).
%%% There exists exactly one Pythagorean triplet for which a + b + c = 1000.
%%% Find the product abc.
%%%
%%% Created :  2 Dec 2008
%%%-------------------------------------------------------------------
-module(p9).

%% API
-export([solution/1]).

%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: solution(N) -> int()
%% Description: Return A*B*C  where
%% A**2 + B**2 = C**2
%% A + B + C = N
%% or -1
%%--------------------------------------------------------------------
solution(N) ->            
    case scan(N, 1, 2, N - 3) of
        {A, B, C} -> A*B*C;
        _ -> -1
    end.

%%====================================================================
%% Internal functions
%%====================================================================
%%Iterate through all possible A,B and C values, where
%%A is the smallest and can't be greater than N/3
%%B can't be greater than (N - A)/2
%%Return {A, B, C} if 
%% A**2 + B**2 = C**2
%% A + B + C = N
scan(N, A, B, C)  ->
    case C > B andalso C*C =:= A*A + B*B of
        true ->
            {A, B, C};
        _ -> case B < (N - A) div 2 of
                 true -> %A is fixed, vary B
                     scan(N, A, B + 1, N - A - B - 1); 
                 _ -> case A < (N div 3) of
                          true -> %Time to increment A
                              scan(N, A + 1, A + 2, N - 2*A - 3);
                          _ -> null
                      end
             end
    end.
